import { use_login_store } from '/src/stores/login.js'

let router=null;

export function setup(r){
    router=r;
}

async function fetch_w1(url,request){
    const login_info=use_login_store();
    
    if(request.headers.satoken==null||request.headers.satoken==""){
        const lg=login_info.get_token();
        if(lg==null||lg==""){
            login_info.set_token("");
            router.push("/login");
        }
        request.headers.satoken=lg;
    }
    try {
        const res= await fetch(url,request);
        if(!res.ok){
            throw(`服务器出错:${res.status}`);
        }
        return res;

    } catch (error) {
        console.log(`请求出错=>${url}  ${error}`);
        throw error;
    }
}

async function fetch_w2(url,request,filter_callback){
    try {
        const res=await fetch_w1(url,request);
        return filter_callback(res);

    } catch (error) {
        console.log(`请求出错=>${url}  ${error}`);
        throw error;
    }
}

//求情json
export async function fetch_x(url,request){

    try {
        const res=await fetch_w1(url,request);
        const s=await res.json();
        if(s.code==`11010`){
            login_info.set_token("");
            router.push("/login");
            throw "去登陆";
        }else if(s.code=="0"){
            return s.res;
        }else{
            throw s.code;
        }
    } catch (error) {
        console.log(`请求出错=>${url}  ${error}`);
        throw error;
    }
    
}

//响应体
export async function fetch_body(url,request){

    return fetch_w2(url,request,(res)=>{
        return res.body;
    });
}

//响应blob
export async function fetch_blob(url,request){

    return fetch_w2(url,request,(res)=>{
        return res.blob();
    });
}
